package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.producerFragment;

import static android.content.Context.MODE_PRIVATE;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.Map;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.ActivityLogin;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity.ActivityAppInfo;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity.ActivityModifyProfile;

public class FragmentProducerProfile extends Fragment {

    Button btnEditProfile;  // 编辑个人信息页面按钮
    Button btnAboutInfo;    // 查看应用信息页面按钮
    Button btnLogOut;       // 退出登录按钮
    TextView tvusername;
    TextView tvemail;

    // 用于处理反馈的SharedPreferences
    SharedPreferences dealerFeedbackPreferences;
    ImageView feedbackIcon;
    TextView feedbackCount;

    public FragmentProducerProfile() {}

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_producer_profile, container, false);

        // 获取SharedPreferences
        dealerFeedbackPreferences = getActivity().getSharedPreferences("ProductFeedback", MODE_PRIVATE);

        // 用户信息
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", "未设置");
        String email = sharedPreferences.getString("email", "未设置");

        tvusername = view.findViewById(R.id.username);
        tvemail = view.findViewById(R.id.email);
        tvusername.setText(username);
        tvemail.setText(email);

        // 编辑个人信息按钮
        btnEditProfile = view.findViewById(R.id.btn_edit_profile);
        btnEditProfile.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ActivityModifyProfile.class);
            startActivity(intent);
        });

        // 查看应用信息按钮
        btnAboutInfo = view.findViewById(R.id.btn_app_info);
        btnAboutInfo.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ActivityAppInfo.class);
            startActivity(intent);
        });

        // 退出登录按钮
        btnLogOut = view.findViewById(R.id.btn_logout);
        btnLogOut.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ActivityLogin.class);
            startActivity(intent);
        });

        // 信封图标和反馈数量
        feedbackIcon = view.findViewById(R.id.feedback_icon);
        feedbackCount = view.findViewById(R.id.feedback_count);

        // 显示反馈数量
        updateFeedbackCount();

        // 信封图标点击事件
        feedbackIcon.setOnClickListener(v -> {
            if (getFeedbackCount() > 0) {
                showFeedbackDialog();  // 显示反馈信息
            } else {
                showNoFeedbackDialog();  // 显示没有反馈的提示
            }
        });

        return view;
    }

    // 获取当前反馈数量
    private int getFeedbackCount() {
        int count = 0;
        Map<String, ?> allFeedback = dealerFeedbackPreferences.getAll();
        for (Map.Entry<String, ?> entry : allFeedback.entrySet()) {
            String key = entry.getKey();
            if (key.endsWith("_name")) {
                int feedback = dealerFeedbackPreferences.getInt(key.replace("_name", ""), 0);
                count += feedback;
            }
        }
        return count;
    }

    // 更新反馈数量显示
    private void updateFeedbackCount() {
        int count = getFeedbackCount();
        if (count > 0) {
            feedbackCount.setText(String.valueOf(count));
            feedbackCount.setVisibility(View.VISIBLE);  // 显示红色小圆
        } else {
            feedbackCount.setVisibility(View.GONE);  // 隐藏红色小圆
        }
    }

    // 显示收到的反馈的弹窗
    private void showFeedbackDialog() {
        StringBuilder feedbackDetails = new StringBuilder();

        Map<String, ?> allFeedback = dealerFeedbackPreferences.getAll();
        for (Map.Entry<String, ?> entry : allFeedback.entrySet()) {
            String key = entry.getKey();
            if (key.endsWith("_name")) {
                String productName = (String) entry.getValue();
                String productId = key.replace("_name", "");
                int feedbackCount = dealerFeedbackPreferences.getInt(productId, 0);

                if (feedbackCount > 0) {
                    feedbackDetails.append(String.format("产品ID: %s - %s, 反馈次数: %d\n", productId, productName, feedbackCount));
                }
            }
        }

        // 创建弹窗显示反馈
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("收到的反馈")
                .setMessage(feedbackDetails.toString())
                .setPositiveButton("确认", (dialog, which) -> {
                    clearFeedback();
                    updateFeedbackCount();  // 更新反馈数量显示
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 如果没有收到反馈，显示提示
    private void showNoFeedbackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("没有反馈")
                .setMessage("目前没有收到任何反馈信息。")
                .setPositiveButton("确定", null)
                .show();
    }

    // 清空所有反馈
    private void clearFeedback() {
        SharedPreferences.Editor editor = dealerFeedbackPreferences.edit();
        editor.clear(); // 清空所有存储的反馈信息
        editor.apply();
    }
}

